package com.yanlight.app.service.impl;

import com.yanlight.app.dal.dao.WxApplyMicroDAO;
import com.yanlight.app.dal.entity.WxApplyMicro;
import com.yanlight.app.request.ApplyMiniRequest;
import com.yanlight.app.response.ApplyStatusResponse;
import com.yanlight.app.service.WxApplyMicroService;
import com.yanlight.support.WxConstants;
import com.yanlight.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

@Service
public class WxApplyMicroServiceImpl implements WxApplyMicroService {

    @Autowired
    private WxApplyMicroDAO wxApplyMicroDAO;

    @Override
    public Map<String, String> apply(ApplyMiniRequest applyEntity) {

        String nonceStr = RandomStringUtil.randomAlphanumeric(32);
        applyEntity.setNonce_str(nonceStr);
        String certificateNo = WxRequestUtil.getCertificateNO(WxConstants.mchId, WxConstants.apiKey);
        applyEntity.setCert_sn(certificateNo);
        applyEntity.setMch_id(WxConstants.mchId);
        String requestCode = RandomStringUtil.randomAlphanumeric(32);
        applyEntity.setBusiness_code(requestCode);

        String applyUserName = applyEntity.getId_card_name();
        String applyPhone = applyEntity.getService_phone();

        applyEntity.rsaEncryptParam();

        SortedMap<String, String> paramsMap = applyEntity.setupParams();
        String apiSignHMAC = SignatureUtil.createApiSignHMAC(paramsMap, WxConstants.apiKey);
        applyEntity.setSign(apiSignHMAC);

        String xmlFromObj = XmlParseUtil.getXmlFromObj(applyEntity);

        String result = WxHttpClientUtil.xmlPost(WxConstants.microUrl, WxConstants.mchId, WxConstants.certPath, xmlFromObj);
        Map<String, String> stringStringMap = XmlUtil.xmlToMap(result);

        if (stringStringMap == null) {
            return null;
        }

        String return_code = stringStringMap.get("return_code");
        String result_code = stringStringMap.get("result_code");

        boolean isRequestSuccess = false;
        if (return_code != null && return_code.equals("SUCCESS") && result_code != null && result_code.equals("SUCCESS")) {
            isRequestSuccess = true;
        }

        if (isRequestSuccess) {
            String applyment_id = stringStringMap.get("applyment_id");
            WxApplyMicro microEntity = new WxApplyMicro();
            microEntity.setBusinessCode(requestCode);
            microEntity.setApplyUserId(0);
            microEntity.setApplymentId(applyment_id);
            microEntity.setCreateTime(new Date());
            microEntity.setStoreAuthName(applyUserName);
            microEntity.setStoreName(applyEntity.getStore_name());
            microEntity.setPhone(applyPhone);

            wxApplyMicroDAO.save(microEntity);
        }

        return stringStringMap;
    }

    @Override
    public String upload(MultipartFile multipartFile) {

        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = null;
        if (originalFilename != null) {
            suffix = "." + originalFilename.split("\\.")[1];
        }

        if (suffix == null) {
            suffix = ".jpg";
        }

        File file = null;
        try {
            file = File.createTempFile(UUIDUtils.random(), suffix);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String mediaId = null;
        if (file != null) {
            mediaId = WxRequestUtil.upload(file, WxConstants.mchId, WxConstants.uploadUrl, WxConstants.apiKey);
        }

        return mediaId;
    }

    @Override
    public ApplyStatusResponse queryApplyStatus(Integer id) {
        WxApplyMicro byId = wxApplyMicroDAO.findById(id);
        ApplyStatusResponse applyStatusResponse = WxRequestUtil.queryApplyStatus(byId.getBusinessCode(), byId.getApplymentId(), WxConstants.apiKey);
        return applyStatusResponse;
    }

    @Override
    public List<WxApplyMicro> queryApplyList(Integer userId) {
        List<WxApplyMicro> wxApplyMicros = wxApplyMicroDAO.queryList(userId);
        return wxApplyMicros;
    }
}
